package com.web;

import com.bean.Comment;
import com.bean.Post;
import com.dao.CommentDao;
import com.dao.PostDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/post")
public class PostServlet extends HttpServlet {
    /**
     * 查询一般用 doGet 方法
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));

        try {
            // 创建 postDao 对象
            PostDao postDao = new PostDao();
            // 创建 commentDao 对象
            CommentDao commentDao = new CommentDao();

            // 实现查询某篇文章方法
            Post post = postDao.getPostById(id);
            // 实现查询某篇文章的所有评论方法
            List<Comment> comments = commentDao.getCommentByPostId(id);

            // 把信息存到 post 中处理
            req.setAttribute("post", post);
            // 把信息存到 comment 中处理
            req.setAttribute("comments", comments);

            // 页面转发
            req.getRequestDispatcher("/post/comment.jsp").forward(req, resp);
        } catch (Exception e) {
            // 把异常打印到控制台
            e.printStackTrace();
            // 把信息存到 error 中处理
            req.setAttribute("error: ", e.getLocalizedMessage());
            // 页面转发
            req.getRequestDispatcher("/post/error.jsp").forward(req, resp);
        }
    }
}
